package repositorios;

import interfaceRepositorio.IRepositorioHora;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import entidades.Hora;
import excecoes.FalhaPersistenciaException;

public class RepositorioHora extends RepositorioAbstrato implements IRepositorioHora {

	private String cadastraStm = "INSERT INTO TBHORA (TBTurno_id, horaInicio, horaFim) VALUES (?, ?, ?)";

	private String consultaStm = "SELECT * FROM TBHORA WHERE TBTurno_id = ? ";
	
	//private String maxStm = "SELECT MAX(id) AS ultimo FROM TBHORA";

	public RepositorioHora() {

	}

	/**
	 * Cadastrar hora.
	 * 
	 * @param hora
	 * @throws FalhaPersistenciaException
	 * @throws SQLException
	 */
	public void cadastrar(Hora hora, int turnoId) throws FalhaPersistenciaException,
			SQLException {

		Connection conn = encontrarConexao();		
		PreparedStatement stm = conn.prepareStatement(cadastraStm);

		stm.setInt(1, turnoId);
		
		stm.setTimestamp(2, hora.getHoraInicio());
		stm.setTimestamp(3, hora.getHoraFim());

		stm.execute();
		stm.close();		
		
	}

	
	public Hora consultar(int turnoId) throws FalhaPersistenciaException,
			SQLException {

		Hora hora = null;
		Connection conn = encontrarConexao();
		PreparedStatement stm = conn.prepareStatement(consultaStm);

		stm.setInt(1, turnoId);
		ResultSet result = stm.executeQuery();
		if (result.next()) {
			hora = new Hora();

			hora.setHoraInicio(result.getTimestamp("horaInicio"));
			hora.setHoraFim(result.getTimestamp("horaFim"));
		}
		stm.close();
		

		return hora;
	}
	
	/*public int consultarMaxId() throws FalhaPersistenciaException, SQLException {
		
		int retorno = 0;
		Connection conn = encontrarConexao();
		PreparedStatement stm = conn.prepareStatement(maxStm);
		ResultSet result = stm.executeQuery();
		
		if(result.next()){
			retorno = result.getInt("ultimo");
			
		}
		
		return retorno;
	}*/

}
